<template>
  <div>
    <div
      ref="triggerRef"
      class='inline-block'
      :data-state="localOpen? 'open' : 'closed'"
    >
      <slot name="trigger"></slot>
    </div>
    <div
      ref="floatingRef"
        :style="floatingStyles" v-show="localOpen">
     <slot></slot>
    </div>
  </div>
</template>
<script setup lang="ts">
import {onMounted, ref,withDefaults} from 'vue';
import {useFloating,autoUpdate,offset,flip,shift,size,type Placement,type OffsetOptions} from '@floating-ui/vue'
import { PortalToFollowAction } from './usePortalToFollow';


type PortalToFollowElemProps = {
  open?:boolean
  placement?: Placement
  offset?: number | OffsetOptions
  onOpenChange?: (open: boolean) => void
  triggerPopupSameWidth?: boolean
}

const props = withDefaults(defineProps<PortalToFollowElemProps>(),{
  offset:10,
  placement: "bottom",
  triggerPopupSameWidth:false,
  open:false
});
const emit = defineEmits(["register"])
const triggerRef = ref(null);
const floatingRef = ref(null);
const localOpen = ref(props.open);
const {floatingStyles} = useFloating(triggerRef,floatingRef,{
    placement:props.placement,
    open:localOpen,
    whileElementsMounted: autoUpdate,
    middleware: [
      offset(props.offset),
      flip({
        crossAxis: props.placement.includes('-'),
        fallbackAxisSideDirection: 'start',
        padding: 5,
      }),
      shift({ padding: 5 }),
      size({
        apply({ rects, elements }) {
          if (props.triggerPopupSameWidth)
            elements.floating.style.width = `${rects.reference.width}px`
        },
      }),
    ],
})

function setOpen(isOpen:boolean = true) {
  localOpen.value = isOpen;
  if(props.onOpenChange) 
    props.onOpenChange(localOpen.value);
}

function toggleOpen() {
  console.log("test");
  localOpen.value = !localOpen.value;
  if(props.onOpenChange) {
    props.onOpenChange(localOpen.value);
  }
}

onMounted(()=> {
  emit("register",{setOpen,toggleOpen} as PortalToFollowAction)
})


</script>